package com.ifudata.dataexpert.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ifudata.dataexpert.constants.SmsConstants;
import com.ifudata.dataexpert.controller.param.AppCollectParam;
import com.ifudata.dataexpert.controller.param.ReportDetailParam;
import com.ifudata.dataexpert.model.ResultMap;
import com.ifudata.dataexpert.util.FileTransBase64Util;
import com.ifudata.dvp.app.api.app.interfaces.IAppManageSV;
import com.ifudata.dvp.app.api.app.param.AppMenuRequest;
import com.ifudata.dvp.app.api.app.param.CollectAppMenusRequest;
import com.ifudata.dvp.app.api.app.param.ReportDetailRequest;
import com.ifudata.dvp.sdk.dubbo.util.DubboConsumerFactory;

/**
 * Created with IntelliJ IDEA
 *
 * @Author libing
 * @Description app controller
 * @Date 2018-10-18
 * @Time 17:12
 */
@RestController
@RequestMapping("/app")
@Scope(value = "prototype")
public class AppController {
	private static final Logger log = LoggerFactory.getLogger(AppController.class);

	/**
	 * 通过congfig key 查询数据集合
	 * 
	 * @param roleId
	 * @return
	 */
	@PostMapping("/getMenu/{key}")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = { "user" })
	@ResponseBody
	public ResultMap getMenu(@PathVariable Long key) {
		log.debug("getMenu/key:{}", key);
		ResultMap resultMap = new ResultMap(true);
		JSONObject object = new JSONObject();
		try {
			AppMenuRequest requset = new AppMenuRequest();
			requset.setParentId(key);
			IAppManageSV sv = DubboConsumerFactory.getService(IAppManageSV.class);
			String re = sv.queryAppMenus(requset);
			object.put("data", JSONArray.parseArray(re));
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} catch (Exception e) {
			log.error("getData 系统异常，异常信息{}", e);
			resultMap.exception().message(SmsConstants.ResMsg.FAILED);
		}
		return resultMap;
	}

	@PostMapping("/getCollectMenu")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = { "user" })
	@ResponseBody
	public ResultMap getCollectMenu(@RequestBody AppCollectParam param) {
		log.debug("getCollectMenu/param:{}", param);
		ResultMap resultMap = new ResultMap(true);
		JSONObject object = new JSONObject();
		try {
			CollectAppMenusRequest requset = new CollectAppMenusRequest();
			requset.setStaffId(resultMap.getStaff().getStaffId());
			requset.setMenuIdList(param.getMenuIds());
			IAppManageSV sv = DubboConsumerFactory.getService(IAppManageSV.class);
			String re = sv.queryCollectAppMenus(requset);
			object.put("data", JSONArray.parseArray(re));
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} catch (Exception e) {
			log.error("getData 系统异常，异常信息{}", e);
			resultMap.exception().message(SmsConstants.ResMsg.FAILED);
		}
		return resultMap;
	}
	
	@PostMapping("/getReportDetail")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = { "user" })
	@ResponseBody
	public ResultMap getReportDetail(@RequestBody ReportDetailParam param) {
		log.debug("getReportDetail/param:{}", param.toString());
		ResultMap resultMap = new ResultMap(true);
		JSONObject object = new JSONObject();
		try {
			ReportDetailRequest requset = new ReportDetailRequest();
			requset.setParentId(param.getParentId());
			
			if( param.getParam()!=null ){
				Map<String, String> map = new HashMap<String, String>();
				for( Entry<String, Object> entry : param.getParam().entrySet() ){
					map.put("${"+entry.getKey()+"}", String.valueOf(entry.getValue()));
				}
				if( map.size()>0 ) requset.setParam(map);
			}
			
			IAppManageSV sv = DubboConsumerFactory.getService(IAppManageSV.class);
			String re = sv.queryReportDetailData(requset);
			object.put("data", JSONObject.parseObject(re));
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} catch (Exception e) {
			log.error("getData 系统异常，异常信息{}", e);
			resultMap.exception().message(SmsConstants.ResMsg.FAILED);
		}
		return resultMap;
	}
	

	/**
	 * 通过路径获取到base64的字符串，然后前台再转换回来
	 * 
	 * @param roleId
	 * @return
	 */
	@PostMapping("/getFile")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = { "user" })
	@ResponseBody
	public ResultMap getFile(@RequestBody Map<String,String> paramMap) {
		String path = paramMap.get("path");
		log.debug("getFile/path:{}", path);
		ResultMap resultMap = new ResultMap(true);
		JSONObject object = new JSONObject();
		try {
			File file = new File(path);
			String name = file.getName();
			int index = name.lastIndexOf(".");
			String fileName = name.substring(0,index);
			String fileType = name.substring(++index);
			
			String base64Str = FileTransBase64Util.fileToBase64(path);
			Map<String,String> map = new HashMap<String,String>();
			map.put("base64", base64Str);
			map.put("fileName", fileName);
			map.put("fileType", fileType);
			object.put("data", JSONObject.parseObject(JSON.toJSONString(map)));
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} catch (Exception e) {
			log.error("getData 系统异常，异常信息{}", e);
			resultMap.exception().message(SmsConstants.ResMsg.FAILED);
		}
		return resultMap;
	}
}
